package com.zjzaki.thingsboard.activity.main;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zjzaki.thingsboard.R;
import com.zjzaki.thingsboard.activity.login.LoginActivity;
import com.zjzaki.thingsboard.activity.bluetooth.DeviceBluetoothListActivity;
import com.zjzaki.thingsboard.adapter.ListViewAdapter;
import com.zjzaki.thingsboard.dao.ThingsBoardDao;
import com.zjzaki.thingsboard.entity.Device;
import com.zjzaki.thingsboard.entity.DeviceServerScope;
import com.zjzaki.thingsboard.util.FileHelper;
import com.zjzaki.thingsboard.util.IPUtil;
import com.zjzaki.thingsboard.util.InternetUtil;
import com.zjzaki.thingsboard.util.Json2ListDevice;
import com.zjzaki.thingsboard.util.Ping;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    /**
     * 退出按钮
     */
    private Button btn_logout;
    /**
     * 工具栏
     */
    private Toolbar toolbar;
    /**
     * 列表视图
     */
    private ListView listView;
    /**
     * 列表视图适配器
     */
    private ListViewAdapter adapter;
    /**
     * 设备列表
     */
    private List<Device> devicesItem;
    /**
     * 下拉刷新
     */
    private SwipeRefreshLayout swipeRefreshLayout;
    /**
     * token
     */
    private String token;
    /**
     * 服务端ip地址
     */
    private String ip = IPUtil.IP;
    /**
     * 服务器通畅检测
     */
    private boolean isServerOk = false;

    /**
     * 设备是否打开网络连接
     */
    private boolean internetConnection;

    /**
     * 与服务器通信是否正常
     */
    private boolean isPing;

    /**
     * 设备共享属性列表
     */
    private List<DeviceServerScope> deviceServerScopesList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //网络检测
        isServerOk = new InternetUtil(this).isInternetConnection();
        //服务器通信检测
        //isPing = Ping.ping(ip, 3, 2);
        //是否能与服务器通信
        //isServerOk = internetConnection && isPing;
        //判断文件是否存在
        boolean exist = new FileHelper(this).isExist("login.txt");
        if(exist){
            //得到token值
            token = new FileHelper(this).getLoginMsg("login.txt").getToken();
        }else{
            Intent deviceIntent = new Intent(MainActivity.this, LoginActivity.class);
            startActivity(deviceIntent);
        }

        //下拉刷新
        swipeRefreshLayout = findViewById(R.id.swipeRefreshLayout);
        //监听刷新状态
        swipeRefreshLayout.setOnRefreshListener(() -> {
            //网络检测
            isServerOk = new InternetUtil(this).isInternetConnection();
            //初始化也面并接收返回值
            boolean b = initView();
            swipeRefreshLayout.setRefreshing(false);
            if(!isServerOk){
                showToast("未连接到网络");
            }else if(b) {
                showToast("刷新成功");
            } else {
                showToast("刷新失败");
            }
        });
        //初始化界面
        initView();
    }

    /**
     * 初始化数据
     */
    private boolean initData() {

        //网络请求
        String devices = ThingsBoardDao.getAllDevice(token);
        //将请求到的信息转换成list列表
        devicesItem = Json2ListDevice.getDeviceList(devices);
        //初始化列表
        deviceServerScopesList = new ArrayList<>();
        //网络请求得到多个设备的服务端属性
        for (Device device : devicesItem) {
            String serverScope = ThingsBoardDao.getServerScope(token, device.getId_id());
            System.out.println(serverScope);
            JSONArray array = JSONObject.parseArray(serverScope);
            //创建设备服务端属性对象
            DeviceServerScope deviceServerScope = new DeviceServerScope();
            //遍历array
            for (int i = 0; i < array.size(); i++) {
                JSONObject jsonObject = array.getJSONObject(i);
                switch (jsonObject.getString("key")) {
                    case "inactivityAlarmTime":
                        deviceServerScope.setInactivityAlarmTime(jsonObject.getLong("value"));
                        break;
                    case "active":
                        deviceServerScope.setActive(jsonObject.getBoolean("value"));
                        break;
                    case "lastConnectTime":
                        deviceServerScope.setLastConnectTime(jsonObject.getLong("value"));
                        break;
                    case "lastDisconnectTime":
                        deviceServerScope.setLastDisconnectTime(jsonObject.getLong("value"));
                        break;
                    case "lastActivityTime":
                        deviceServerScope.setLastActivityTime(jsonObject.getLong("value"));
                        break;
                }
            }
            //添加到list列表
            deviceServerScopesList.add(deviceServerScope);
        }
        if (0 != devicesItem.size()) {
            return true;
        }
        return false;
    }

    /**
     * 刷新界面
     *
     * @return 是否刷新成功
     */
    public boolean initView() {
        System.out.println(isServerOk);

        boolean b = false;
        if (isServerOk) {
            //初始化数据
            b = initData();
            //列表视图
            listView = findViewById(R.id.listview);
            listView.setAdapter(adapter = new ListViewAdapter(this, devicesItem, deviceServerScopesList));

            //设置列表事件监听
            listView.setOnItemClickListener((parent, view, position, id) -> {
                //Toast.makeText(MainActivity.this, "点击Item位置" + position, Toast.LENGTH_SHORT).show();
                // 跳转
                Intent deviceIntent = new Intent(MainActivity.this, DeviceInfoActivity.class);
                // 设置设备id，将设备id传到新界面
                deviceIntent.putExtra("deviceId", devicesItem.get(position).getId_id());
                //将设备名，传入到新界面
                deviceIntent.putExtra("deviceName", devicesItem.get(position).getName());

                startActivity(deviceIntent);
            });
        }

        //设置动作栏
        toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        return b;
    }

    /**
     * 创建菜单栏选项
     *
     * @param menu
     * @return
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        //膨胀的菜单;这将向操作栏添加项目(如果操作栏存在的话)。
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    /**
     * 菜单栏按钮点击事件
     *
     * @param item 选项
     * @return 返回是否选中
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        //处理操作栏项目点击这里。只要你在AndroidManifest.xml中指定了父活动，操作栏就会自动处理HomeUp按钮的点击。
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        //退出登录
        if (id == R.id.btn_logout) {
            //删除登录信息
            FileHelper fileHelper = new FileHelper(getApplicationContext());
            boolean b = fileHelper.deleteFile("login.txt");
            if (b) {
                startActivity(new Intent(MainActivity.this, LoginActivity.class));
            } else {
                Toast.makeText(MainActivity.this, "退出失败", Toast.LENGTH_SHORT).show();
            }
            return true;
        } else if (id == R.id.btn_bluetooth) {
            startActivity(new Intent(MainActivity.this, DeviceBluetoothListActivity.class));
        }

        return super.onOptionsItemSelected(item);
    }

    /**
     * 显示页面提示消息
     * @param msg 提示消息
     */
    private void showToast(String msg){
        Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
    }
}